<template>
  <el-form
    size="large"
    :rules="FORM_RULES"
    ref="formRef"
    :model="formData"
    label-width="180px"
    class="form-data"
    scroll-to-error
  >
    <div class="form-data-title">通用问卷维护</div>
    <el-form-item prop="bt" label="标题">
      <el-input clearable placeholder="请输入标题" v-model="formData.bt"></el-input>
    </el-form-item>
    <el-form-item prop="num" label="抽取数量">
      <el-input-number v-model="formData.num" :step="5" :min="0"></el-input-number>
    </el-form-item>
    <el-form-item prop="year" label="调查年份">
      <el-date-picker
          v-model="formData.year"
          type="year"
          placeholder="请选择调查年份"
          value-format="YYYY"
        />
    </el-form-item>
    <el-form-item prop="entryDate" label="生效日期">
      <el-date-picker
        v-model="formData.entryDate"
        type="daterange"
        unlink-panels
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="max-width: 600px"
      />
    </el-form-item>

    <div class="form-sub-title">问卷题目</div>
    <div v-for="(domain, index) in formData.questions" class="sub-form"
          :key="domain.id">
      <el-row>
      <el-col :span="1" class="sub-order">
        <span>{{index+1}}</span>
      </el-col>
      <el-col :span="19">
        <el-form-item
          label="问题"
          :prop="'questions.' + index + '.bt'"
          :rules="{
            required: true,
            message: '请维护问卷问题',
            trigger: 'change',
          }"
        >
          <el-input clearable placeholder="请维护问卷问题" v-model="domain.bt"></el-input>
        </el-form-item>
        <el-form-item
          label="描述"
          :prop="'questions.' + index + '.describe'"
        >
          <el-input clearable placeholder="请维护描述" v-model="domain.describeContent"></el-input>
        </el-form-item>
        <el-form-item
          label="类型"
          :prop="'questions.' + index + '.type'"
          :rules="{
            required: true,
            message: '请选择问卷类型',
            trigger: 'change',
          }"
        >
          <el-radio-group v-model="domain.type" @change="getTypeValue(domain)">
            <el-radio v-for="item in typeList" :key="item" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="限选数量"
          :prop="'questions.' + index + '.limitChecked'"
          v-show="domain.type == 2"
        >
          <el-input-number v-model="domain.limitChecked" :step="1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item
          :prop="'questions.' + index + '.code'"
          v-if="domain.type < 3"
          label="数据选项"
          :rules="{
            required: true,
            message: '请选择数据选项',
            trigger: 'change',
          }"
          >
          <el-tree-select
          filterable
          v-model="domain.code"
          :data="codeTree"
           @change="getCodeValue(domain)"
          :render-after-expand="true"></el-tree-select>
        </el-form-item>
        <el-form-item
          label="校验规则"
          :prop="'questions.' + index + '.validateRule'"
        >
          <el-input clearable placeholder="请输入校验规则（正则表达式）" v-model="domain.validateRule"></el-input>
        </el-form-item>
        <el-form-item
          label="校验失败提示"
          :prop="'questions.' + index + '.validateRuleTip'"
          v-if="domain.validateRule"
        >
          <el-input clearable placeholder="请输入校验失败提示语" v-model="domain.validateRuleTip"></el-input>
        </el-form-item>
        <el-form-item
          label="默认值"
          :prop="'questions.' + index + '.replyDefault'"
        >
          <el-input clearable placeholder="请输入答案默认值" v-model="domain.replyDefault"></el-input>
        </el-form-item>
        <el-form-item
          label="排序"
          :prop="'questions.' + index + '.showOrder'"
          :rules="{
            required: true,
            message: '请维护排序',
            trigger: 'change',
          }"
        >
          <el-input-number v-model="domain.showOrder" :step="2"></el-input-number>
        </el-form-item>
      </el-col>
      <el-col :span="4" class="sub-button">
         <el-button type="primary" size="large" @click="addItem" v-if="index+1 === formData.questions.length">新增</el-button>
         <el-button type="primary" size="large" @click="copyItem(domain)" v-if="index+1 === formData.questions.length">复制</el-button>
         <el-popconfirm :title="showContent" @confirm="delItem(domain,index)" v-if="formData.questions.length>1">
            <template #reference>
              <el-button type="warning" size="large">删除</el-button>
            </template>
          </el-popconfirm>
      </el-col>
    </el-row>
    </div>

    <div class="form-footer">
      <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
      <el-button type="info" @click="handleClose">关闭</el-button>
    </div>
  </el-form>

</template>
<script setup>
import useStore from '@/store'
import { useRoute, useRouter } from 'vue-router'
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { getQuestionConfig, saveQuestionConfig, removeQuestionSub } from '@/api/business/questionscommon/questionconfig/QuestionConfig'
import { QuestionConfigBean, FORM_RULES, QuestionConfigSubBean } from '@/model/business/questionscommon/questionconfig/QuestionConfigConstants'
import { getCodeGroupTree, getCodeTree, getCode } from '@/api/system/code/CodeManager'
import { getArrayText } from '@/utils/common'

import '@/style/form.less'
import { prop } from 'vue-class-component'

const codeTree = ref([])
const typeList = ref([])// 1单选 2多选 3问答
const route = useRoute()
const router = useRouter()
const { menuStore } = useStore()
const formRef = ref()
const formData = ref({
  ...QuestionConfigBean,
  questions: [{
    ...QuestionConfigSubBean,
    showOrder: 1,
    type: '1',
    typeText: '单选题'
  }]
})
const subSelectIndex = ref(0)

const addItem = () => {
  formData.value.questions.push({
    ...QuestionConfigSubBean,
    showOrder: maxOrder(),
    type: '1',
    typeText: '单选题'
  })
}

const copyItem = (item) => {
  formData.value.questions.push({
    ...item,
    showOrder: maxOrder(),
    id: ''
  })
}

const maxOrder = () => {
  let order = 1
  formData.value.questions.forEach(sub => {
    if (sub.showOrder > order) {
      order = sub.showOrder
    }
  })

  return order + 2
}

const showContent = computed(() => {
  return '是否要删除?'
})

const delItem = (item, index) => {
  formData.value.questions.splice(index, 1)
  if (item.id) {
    removeQuestionSub(item.id)
  }
}

const submitForm = (formEl) => {
  if (!formEl) return
  if (formData.value.num > formData.value.questions.length) {
    ElMessage.error('抽取数量不能大于问题数量')
    return
  }
  formEl.validate((valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '保存中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      saveQuestionConfig(formData.value).then(() => {
        loading.close()
        ElMessage.success('保存成功！')
        if (!formData.value.id) {
          handleClose()
        }
      }).catch(() => {
        loading.close()
        ElMessage.error('保存失败！')
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const handleClose = () => {
  menuStore.closeCurrentPage(route, router)
}

onMounted(() => {
  const id = route.query.id

  if (id) {
    const loading = ElLoading.service({
      lock: true,
      text: '数据加载中……',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    getQuestionConfig(id).then(data => {
      formData.value = { ...data }
      loading.close()
    })
  }
  // 题目类型，单选多选
  getCode('01J1P9G75K27ZDDRA1DVC040B7').then(data => {
    typeList.value = data
  })
  // 问题数据选项代码树
  getCodeTree('01J1HBM6ZY3PRBJ7V74K68Y96M').then(data => {
    codeTree.value = data
  })
})

const getTypeValue = (item) => {
  item.typeText = getArrayText(item.type, typeList.value)
}

const getCodeValue = (item) => {
  item.codeText = filterCodeTreeValue(item.code, codeTree.value)
}

const filterCodeTreeValue = (code, array) => {
  let obj = ''
  array.forEach(function (item) {
    if (code === item.value) {
      obj = item.label
    } else if (item.children && item.children.length > 0) {
      const cObj = filterCodeTreeValue(code, item.children)
      if (cObj) {
        obj = cObj
      }
    }
  })
  return obj
}

</script>
<style lang="scss">

.sub-order{
  display: flex;
  align-items: center;
  justify-content: center;
}

.sub-button button:first-child{
  margin-left: 10px;
}

.sub-form{
  width:100%;
  padding:20px 0 ;
  border-top: 1px solid var(--el-border-color)
}

.sub-form .el-form-item--large{
  margin-bottom: 15px;
}
</style>
